import { memo, useEffect, useState } from "react";
import { LeaveWordWrapper } from "./style";
import SearchItems, {
  type ISearchFormItem,
} from "../../../commponts/SearchItems";
import { useAppDispatch, useAppSelector } from "../../../store";
import { fetchDeptListAction } from "../../../store/modules/patient";
import { fetchLeaveWordListAction } from "../../../store/modules/leaveWord";
import { Button, Message, Modal, Popover, Table } from "@arco-design/web-react";
import downloadFile from "../../../utils/exportData";
import { exportLeaveWord } from "../../../service/modules/leaveWord";
import dayjs from "dayjs";

const LeaveWordPage = () => {
  const dispatch = useAppDispatch();
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [visible, setVisible] = useState(false);
  const [searchParams, setSearchParams] = useState<{
    leaveWordTitle: string;
    deptName: number;
  }>({
    leaveWordTitle: "",
    deptName: 0,
  });
  useEffect(() => {
    dispatch(fetchDeptListAction());
    dispatch(
      fetchLeaveWordListAction({ pageNum: pageNum, pageSize: pageSize })
    );
  }, [dispatch]);
  const { leaveWordList, total } = useAppSelector((state) => state.leaveWord);
  const { deptList } = useAppSelector((state) => state.patient);

  // console.log(leaveWordList, deptList);

  const searchItems: ISearchFormItem[] = [
    {
      type: "input",
      field: "leaveWordTitle",
      label: "留言标题",
      placeholder: "请输入食谱标题",
    },
    {
      type: "select",
      field: "deptName",
      label: "科室名称",
      placeholder: "请选择科室",
      options: deptList?.map((item) => {
        return { label: item.deptName, value: item.deptId };
      }),
    },
  ];

  /**
   * @留言数据表单展示
   */
  const columns = [
    {
      title: "留言id",
      dataIndex: "leaveWordId",
    },
    {
      title: "留言标题",
      dataIndex: "leaveWordTitle",
    },
    {
      title: "用户名称",
      dataIndex: "sendUserName",
    },
    {
      title: "留言内容",
      dataIndex: "leaveWordContent",
      render: (vlaue: string, record: any) => {
        return (
          <Popover
            trigger="hover"
            content={<span>{record.leaveWordContent}</span>}
          >
            {record.leaveWordContent}
          </Popover>
        );
      },
    },
    {
      title: "科室名称",
      dataIndex: "deptName",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
  ];
  const data = leaveWordList?.map((item) => {
    return {
      id: item.id,
      leaveWordId: item.id,
      leaveWordTitle: item.title || "暂无标题",
      sendUserName: item.userName || "未知用户",
      leaveWordContent: item.content,
      deptName: item.deptName,
      createTime: item.createTime,
    };
  });

  /**
   * @搜索获取过滤信息
   */
  const handleSearch = (values: any) => {
    // console.log(values);
    setSearchParams({
      leaveWordTitle: values.leaveWordTitle || "",
      deptName: values.deptName || 0,
    });
  };

  /**
   * @选择框
   */

  const onSelectChange = (newSelectedRowKeys: any[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
  };
  const rowSelection = {
    onChange: onSelectChange,
    selectedRowKeys,
  };
  /**
   * @过滤数据
   */
  const filteredData = data?.filter((item) => {
    if (Object.keys(searchParams).length === 0) return data;
    const titleMatch =
      !searchParams.leaveWordTitle ||
      item?.leaveWordTitle?.includes(searchParams.leaveWordTitle);
    const deptMatch =
      !searchParams.deptName || item?.deptName?.includes(searchParams.deptName);
    return titleMatch && deptMatch;
  });
  const handleDelete = () => {
    // console.log(1);
    dispatch(fetchLeaveWordListAction(selectedRowKeys[0]));
    setVisible(false);
  };

  /**
   *@导出
   */
  // const exportLeaveWord = async () => {
  //   await dispatch(
  //     fetchExportLeaveWordAction({
  //       pageNum,
  //       pageSize,
  //     })
  //   );
  // };
  const handleExport = async () => {
    try {
      if (filteredData.length) {
        const leaveWordRes = await exportLeaveWord({ pageNum, pageSize });
        downloadFile(
          leaveWordRes,
          `留言列表_${dayjs().format("YYYYMMDD")}.xlsx`
        );
      }
      Message.success("导出成功");
    } catch (err) {
      Message.error("导出失败");
      console.log(err);
    }
  };

  return (
    <LeaveWordWrapper>
      <Modal
        title="友情提醒"
        visible={visible}
        onOk={handleDelete}
        onCancel={() => {
          setVisible(false);
          setSelectedRowKeys([]);
        }}
        autoFocus={false}
        focusLock={true}
      >
        <p style={{ textAlign: "center" }}>你确定要删除这条留言吗</p>
      </Modal>
      <SearchItems items={searchItems} onSearch={handleSearch} />

      <div className="centerWrapper">
        <div className="btn">
          <Button
            status="danger"
            disabled={selectedRowKeys.length < 1}
            onClick={() => setVisible(true)}
          >
            删除
          </Button>
        </div>
        <div className="btn">
          <Button status="warning" onClick={handleExport}>
            导出
          </Button>
        </div>
      </div>
      <div className="showTable">
        <Table
          rowSelection={rowSelection}
          rowKey={(record) => record.id}
          columns={columns}
          data={filteredData}
          style={{ userSelect: "none" }}
          pagination={{
            total: total,
            sizeOptions: [10, 20, 30],
            showJumper: true,
            showTotal: () => `共${total}条`,
            sizeCanChange: true,
            onChange: (pageNum, pageSize) => {
              // console.log(pageNum, pageSize);
              setPageNum(pageNum);
              setPageSize(pageSize);
            },
          }}
        ></Table>
      </div>
    </LeaveWordWrapper>
  );
};
export default memo(LeaveWordPage);
